package com.whq.knowverywell.business.http;

import org.json.JSONObject;

import android.content.Context;

import com.whq.knowverywell.business.model.ConfResult;
import com.whq.knowverywell.util.LogUtil;
import com.whq.knowverywell.util.NetworkUtil;
import com.whq.knowverywell.util.constant.CfgConstant;
import com.whq.knowverywell.util.httpclient.HttpClientUtil;
import com.whq.knowverywell.util.httpclient.HttpResult;

/**
 * 读取配置工具类
 * @author wanghuaiqiang
 *
 */
public class ConfRequestUtil  {
	protected static final String TAG = ConfRequestUtil.class.getSimpleName();

	/**
	 * 从服务器获取所有配置
	 * @param context
	 * @return
	 */
	public static ConfResult getConfFromServer(Context context) {
		if (context == null) {
			return null;
		}
		if (!NetworkUtil.isNetworkAvailable(context)) {
            return null;
        }
		
		String path = CfgConstant.SERVER_CONTEXT + "/config/query";
		String req = "version=" + CfgConstant.SERVER_API_VERSION + 
        		"&source=" + CfgConstant.SERVER_API_SOURCE ;
		
		HttpResult httpResult = HttpClientUtil.callServer(context, CfgConstant.SERVER_HOST, false, path, req, "UTF-8");
		if ( (httpResult != null) && (httpResult.checkCode()) ) {
			try {
				JSONObject jsonObj = new JSONObject(httpResult.getResp());
				int resultCode = jsonObj.optInt("resultCode", -1);
				if (resultCode == 0) {
					JSONObject jsonData = jsonObj.optJSONObject("data");
					if (jsonData == null) {
						return null;
					}
					
					ConfResult ret = new ConfResult();
					ret.setAppVersionCode(jsonData.optInt("app-android-version-code", 1));
					ret.setAppVersionName(jsonData.optString("app-android-version-name", ""));
					ret.setAppApkName(jsonData.optString("app-android-apk", ""));
					ret.setAppChgLog(jsonData.optString("app-android-chglog", ""));
					
					return ret;
				}
			} catch (Exception ex) {
				LogUtil.e(TAG, "解析json串[" + httpResult.getResp() + "]出错:", ex);
			}
		}
		return null;
	}

}